namespace Warehouse

open System.Windows.Data
open System.Linq
open FSharp.Windows
open Warehouse.Controls

type BrandsEvents = 
    | Save of (unit -> unit)
    | New
    | Delete
    | SelectedChanged of BrandDetailsModel
    | PrintBarCodes

type BrandView() as this = 
    inherit View<BrandsEvents, BrandModel, BrandWindow>()
    
    let items = this.Control.Items
    let clientDefaultRegularPct = this.Control.ClientDefaultRegularPct
    let clientDefaultLitrSizePct = this.Control.ClientDefaultLitrSizePct
    let vendorDefaultRegularPct = this.Control.VendorDefaultRegularPct
    let vendorDefaultLitrSizePct = this.Control.VendorDefaultLitrSizePct

    do
        items.DisplayMemberPath <- "Name"
        for tb in [ clientDefaultRegularPct; clientDefaultLitrSizePct; vendorDefaultRegularPct; vendorDefaultLitrSizePct] do
            tb.EnsureDecimal()

    override this.EventStreams = 
        [
            yield! [
                this.Control.Save, Save this.OK
                this.Control.New, New
                this.Control.Delete, Delete
                this.Control.PrintBarCodes, PrintBarCodes
            ] 
            |> List.ofButtonClicks

            yield items.SelectionChanged |> Observable.choose (fun event -> 
                let event = event.RemovedItems.Cast().SingleOrDefault()
                if event <> null then Some(SelectedChanged event) else None
            )
        ]

    override this.SetBindings model =
        Binding.FromExpression 
            <@
                items.ItemsSource <- model.Items
                items.SelectedItem <- model.SelectedBrand
                this.Control.BrandName.Text <- model.SelectedBrand.Name

                this.Control.Save.IsEnabled <- isNotNull model.SelectedBrand 
                this.Control.Delete.IsEnabled <- model.IsDeleteEnable
                this.Control.PrintBarCodes.IsEnabled <- isNotNull model.SelectedBrand

                clientDefaultLitrSizePct.Text <- string model.SelectedBrand.ClientDefaultLitrSizePct
                clientDefaultRegularPct.Text <- string model.SelectedBrand.ClientDefaultRegularPct
                vendorDefaultRegularPct.Text <- string model.SelectedBrand.VendorDefaultRegularPct
                vendorDefaultLitrSizePct.Text <- string model.SelectedBrand.VendorDefaultLitrSizePct
            @>        
            
